<template>
  <div v-if="is_info" class="text-ellipsis" :title="date_str">{{date_str}}</div>
  <div v-else class="form_item-datetime" style="line-height: 0;">
    <input type="hidden" :name="name" :value="value">
    <el-date-picker v-model="this_value" :format="format.template" :size="size" :type="format.type" @change="onchange"></el-date-picker>
  </div>
</template>

<script>
import s94Mjs from "s94-js";

export default {
  _title_: '时间戳',
  _can_config_: true,
  _can_form_param_: true,
  _can_where_param_: true,
  name: "datetime",
  props: ['name', 'value', 'config', 'is_info', 'size', 'is_list'],
  emits: ['update:value', 'change'],
  data(){
    let format = this.decode_format();
    return {
      format: format,
      this_value: this.value*1000,
      need_display: true,
    };
  },
  methods: {
    onchange(date){
      let v = date ? Math.floor(date.getTime()/1000) : "";
      this.need_display = false;
      setTimeout(()=>{this.need_display = true;},5)
      this.$emit('update:value', v);
      this.$emit('change', v);
    },
    decode_format(){
      let config = this.config || 'Y-M-D H:I:S';
      let res = {}
      res.type = 'year';
      if (/[his]/i.test(config)){
        res.type = 'datetime';
      }else if(/d/i.test(config)){
        res.type = 'date';
      }else if(/m/i.test(config)){
        res.type = 'month';
      }
      let map = {Y:'YYYY',y:'YYYY',M:'MM',m:'M',D:'DD',d:'D',H:'HH',h:'H',I:'mm',i:'m',S:'ss',s:'s'}
      res.template = config.replace(/[YMDHISymdhis]/g, function (ms){
        return map[ms];
      })
      return res;
    }
  },
  watch: {
    config(v, oldV){
      this.format = this.decode_format();
    },
    value(){
      if (!this.need_display) return;
      this.this_value = this.value*1000;
    }
  },
  computed: {
    date_str(){
      if (!this.value) return '';
      let fmt = this.config || 'Y-M-D H:I:S';
      return  s94Mjs.date(fmt, this.value*1000);
    }
  },
  mounted() {
  }
}
</script>

<style scoped>

</style>